import { Context } from 'koa';
import { getManager } from 'typeorm';
  
import { Client } from '../entity/client';
import { Statistics } from '../entity/statistics';


export default class ClientController {

  /**
   * 返回所有的client
   * @param ctx 
   */
  public static async listClients(ctx: Context) {
    const clientRepository = getManager().getRepository(Client);
    const users = await clientRepository.find();
    
    if (users) {
      ctx.status = 200;
      ctx.body = users;
    } else {
      ctx.status = 500;
    }
    
  }

  /**
   * 新增客户，Post方法
   * @param ctx 上下文
   */
  public static async appendClient(ctx: Context) {
    const clientRepository = getManager().getRepository(Client);
    const statisticsRepository = getManager().getRepository(Statistics);

    const newClient = new Client();

    // 得到缩写，用缩写和id构成clientId
    const clientAbbr: string = ctx.request.body.clientAbbr;
    const clientAmount = (await statisticsRepository.query(`SELECT clientAmount FROM statistics LIMIT 1`))[0].clientAmount;
    const newClientNo = clientAmount + 1;
    const clientId = clientAbbr + (10000 + newClientNo).toString().substr(1);

    newClient.id = clientId;
    newClient.name = ctx.request.body.name;
    newClient.address = ctx.request.body.address;
    newClient.phone = ctx.request.body.phone;
  
    // 保存到数据库
    const client = await clientRepository.save(newClient);
    
    if (client) {
      await statisticsRepository.update(1, {clientAmount: newClientNo});
      ctx.status = 201;
      ctx.body = client;
    } else {
      ctx.status = 500;
    }
  }

  
  /**
   * 根据客户ID，查找客户，Get方法
   * @param ctx 上下文
   */
  public static async checkClient(ctx: Context) {
    const clientRepository = getManager().getRepository(Client);
    
    // 要查找的对象
    const id: string = ctx.params.id;
  
    // 保存到数据库
    const client = await clientRepository.findOne(id);
    
    if (client) {
      ctx.status = 200;
      ctx.body = client;
    } else {
      ctx.status = 500;
    }
  }

  /**
   * 更新客户信息，目前只能更新客户地址和电话
   * @param ctx 上下文
   */
  public static async updateClient(ctx: Context) {
    const clientRepository = getManager().getRepository(Client);
    
    // 要修改的对象
    const id: string = ctx.params.id;

    // 更新
    await clientRepository.update(id, ctx.request.body);
    // 获得更新之后的对象
    const updatedUser = await clientRepository.findOne(id);
    
    if (updatedUser) {
      ctx.status = 200;
      ctx.body = updatedUser;
    } else {
      ctx.status = 500;
    }
  }

  /**
   * 删除客户，根据客户的clientId
   * @param ctx 上下文
   */
  public static async deleteClient(ctx: Context) {
    const clientRepository = getManager().getRepository(Client);

    // 要删除的客户
    const clientId = ctx.params.id;
    await clientRepository.delete(clientId);
  
    ctx.status = 204;
    ctx.body = `删除用户 ${clientId}`;
  }

}